// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");

const formatData = (results) => {
	try {
		const data = results.map(o => ({
			...o,
			create: moment(o.create).format("YYYY-MM-DD HH:mm:ss")
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table}`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("无评论信息！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 文章发布
exports.Add = async (req, res, table) => {
	const { content, image_path, anime_id, galgame_id, article_id } = req.body;
	const info = { content, image_path, anime_id, galgame_id, article_id, creator: req.user.id };
	try {
		const sqlStr = `INSERT INTO ${table} SET ?`;
		const [results] = await mysql.query(sqlStr, [info]);
		if (results.affectedRows !== 1) return res.error("评论失败");
		return res.success("评论成功");
	} catch (err) {
		return res.error(err);
	}
};